import 'package:flutter/material.dart';
import 'package:mysql_client/mysql_client.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TiDB Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
      ),
      home: const MyHomePage(title: 'TiDB 数据库操作'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Map<String, dynamic>> _records = [];
  final _nameController = TextEditingController();
  final _ageController = TextEditingController();
  MySQLConnection? _connection;

  @override
  void initState() {
    super.initState();
    _connectToDatabase();
  }

  Future<void> _connectToDatabase() async {
    try {
      _connection = await MySQLConnection.createConnection(
        host: 'gateway01.ap-northeast-1.prod.aws.tidbcloud.com',     // TiDB 服务器地址
        port: 4000,            // TiDB 默认端口
        userName: '2EkJ3qPkUKd6Ahe.root',      // TiDB 默认用户名
        password: 'NDgLbKApUss9h3sK',          // TiDB 默认密码为空
        databaseName: 'test',  // 数据库名称
      );

      await _connection!.connect();
      
      // 创建表（如果不存在）
      await _connection!.execute('''
        CREATE TABLE IF NOT EXISTS users (
          id INT AUTO_INCREMENT PRIMARY KEY,
          name VARCHAR(255) NOT NULL,
          age INT NOT NULL
        )
      ''');
      
      _loadRecords();
    } catch (e) {
      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('数据库连接错误'),
            content: SelectableText(e.toString()),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  Future<void> _loadRecords() async {
    try {
      final result = await _connection!.execute('SELECT * FROM users');
      setState(() {
        _records = result.rows.map((row) => {
          'id': row.colAt(0),
          'name': row.colAt(1),
          'age': row.colAt(2),
        }).toList();
      });
    } catch (e) {
      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('加载数据错误'),
            content: SelectableText(e.toString()),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  Future<void> _addRecord() async {
    if (_nameController.text.isEmpty || _ageController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请填写所有字段')),
      );
      return;
    }

    try {
      final name = _nameController.text;
      final age = int.parse(_ageController.text);
      
      await _connection!.execute(
        'INSERT INTO users (name, age) VALUES ("$name", $age)',
      );
      
      _nameController.clear();
      _ageController.clear();
      _loadRecords();
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('添加成功')),
      );
    } catch (e) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('添加数据错误'),
          content: SelectableText(e.toString()),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _ageController.dispose();
    _connection?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(
                labelText: '姓名',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _ageController,
              decoration: const InputDecoration(
                labelText: '年龄',
                border: OutlineInputBorder(),
              ),
              keyboardType: TextInputType.number,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _addRecord,
              child: const Text('添加记录'),
            ),
            const SizedBox(height: 16),
            const Text('数据库记录：', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            Expanded(
              child: ListView.builder(
                itemCount: _records.length,
                itemBuilder: (context, index) {
                  final record = _records[index];
                  return ListTile(
                    title: Text('姓名: ${record['name']}'),
                    subtitle: Text('年龄: ${record['age']}'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
